package online.inote.naruto.utils.http;

import com.alibaba.fastjson.JSON;
import lombok.Builder;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Response;
import online.inote.naruto.exception.HttpException;
import online.inote.naruto.utils.StringUtils;
import org.apache.commons.collections4.MapUtils;

import java.io.IOException;
import java.util.Objects;

/**
 * @description 同步请求
 * @author gaopengsui@creditease.cn
 * @date 2021/10/08 4:16 下午
 */
@Builder
public class SyncRequest extends Request {

  private OkHttpClient client;
  private ResultConvertor convertor;

  /**
   * GET请求
   *
   * @return
   */
  @Override
  public Result get() {
    Response response = null;
    try {
      response = client.newCall(buildRequest().build()).execute();
    } catch (IOException e) {
      throw new HttpException("http请求失败", e);
    }
    return Result.builder().response(response).convertor(convertor).build();
  }

  /**
   * POST请求
   *
   * @return
   */
  @Override
  public Result post() {
    Response response = null;

    try {
      response = client.newCall(buildRequest().post(buildBody()).build()).execute();
    } catch (IOException e) {
      throw new HttpException("http请求失败", e);
    }

    return Result.builder().response(response).convertor(convertor).build();
  }

  /**
   * PUT请求
   *
   * @return
   */
  @Override
  public Result put() {
    return null;
  }

  /**
   * DELETE请求
   *
   * @return
   */
  @Override
  public Result delete() {
    return null;
  }

  private okhttp3.Request.Builder buildRequest() {
    String urlParams = StringUtils.convertToUrlParams(this.urlParamMap);

    okhttp3.Request.Builder builder =
        new okhttp3.Request.Builder()
            .url(this.targetUrl + (StringUtils.isBlank(urlParams) ? "" : urlParams));

    if (MapUtils.isNotEmpty(this.headerParamMap)) {
      this.headerParamMap.forEach((key, val) -> builder.addHeader(key, val));
    }

    return builder;
  }

  private RequestBody buildBody() {
    RequestBody body = null;

    if (Objects.nonNull(this.requestBody)) {
      if (this.requestBody instanceof String) {
        body = RequestBody.create(this.mediaType, this.requestBody.toString());
      } else {
        body = RequestBody.create(this.mediaType, JSON.toJSONString(this.requestBody));
      }
    } else if (MapUtils.isNotEmpty(this.requestBodyMap)) {
      body = RequestBody.create(this.mediaType, JSON.toJSONString(this.requestBodyMap));
    } else {
      body = RequestBody.create(this.mediaType, "{}");
    }

    return body;
  }
}
